<!-- 
 素材库页面之外的弹窗中使用的组件 
-->
<template>
  <a-spin :spinning="isLoading">
    <div class="top_con">
      <div class="top_con-left">
        <div v-if="!isTip && !is_tag" class="left_back">
          <LeftOutlined @click="backPrevious" />
          <span style="margin-left: 5px" @click="backPrevious">返回</span>
          <span style="margin-left: 15px; color: #000">{{ folder_name }}</span>
        </div>

        <div v-else style="color: #fff">1</div>
      </div>

      <div class="top_con-right">
        <a-checkbox
          v-if="multiple"
          v-model:checked="checkAll"
          :indeterminate="indeterminate"
          @change="onCheckAllChange"
        >
          全选
        </a-checkbox>
        <a-checkbox
          v-if="multiple"
          v-model:checked="checkeach"
          :indeterminate="indeterminate"
          @change="downChange"
        >
          反选
        </a-checkbox>

        <div class="right_material_count">已选中{{ selectNum || materialCount }}素材</div>
      </div>
    </div>

    <div class="material_con" :style="dynamicStyle" >
      
      <!-- 上传操作 -->
      <div class="upload_mater" v-if="!is_tag">
        <a-upload
          class="model_upload"
          v-model:file-list="fileList"
          :before-upload="beforeUpload"
          :multiple="true"
          name="file"
          :accept="getAcceptValue"
          :customRequest="customRequest"
          :disabled="loading || noenzu"
        >
          <template #itemRender="{ file, actions }"> </template>
          <div class="model_upload_text">
            <div class="model_upload_top">
              <plus-outlined style="font-size: 16px; margin-right: 10px" />
              <div>从本地文件夹选择</div>
            </div>
            <div v-if="Dfolder_type == 'video'">
              视频格式: mov/mp4/3gp(文件≤1G、时长≤60分钟)
            </div>
            <div v-if="Dfolder_type == 'image'">
              图片格式: jpg/jpeg/png/gif,图片尺寸50~8000,单张图片不可大于20M
            </div>
            <div v-if="Dfolder_type == 'audio'">音频格式: {{extension}}</div>
            <!-- <div v-if="Dfolder_type == 'audio'">音频格式: mp3、m4a、wav</div> -->
          </div>
        </a-upload>
      </div>

      <!-- 上传图片的预览 -->
      <div
        v-if="Dfolder_type == 'image'"
        class="updatevideo_All"
        v-for="(item, index) in updateImage"
        :key="index"
      >
        <div class="updatevideo_item" @click="previewClick(item)">
          <img :src="item.url" alt="" class="see_img" />
          <!-- 上传失败 -->
          <div class="up_fin" v-if="item.isfailed">
            <a-tag color="red">上传失败</a-tag>
          </div>

          <!-- 已上传 -->
          <div class="up_fin" v-if="item.up_finish">
            <a-tag color="success">已上传</a-tag>
          </div>
        </div>

        <!-- 进度条  上传中-->
        <div class="progress_item" v-if="item.up_ing && !item.up_finish">
          <a-progress
            :percent="isAlionline || isOss ? item.uploadProgress : 100"
            :showInfo="isAlionline || isOss"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
        </div>

        <!-- 进度条  待上传 -->
        <div class="before_progress_item" v-if="!item.up_ing">
          <a-progress
            style="width: 78%"
            percent="0"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
          <div class="wait_upload">待上传</div>
        </div>

        <div class="updatevideo_bottom">
          <div class="updatevideo_bottom_left">
            {{ item.name }}
          </div>

          <div class="updatevideo_bottom_right">
            <delete-outlined
              v-if="!loading"
              class="updatevideo_icon_right"
              @click="del_upImage(index)"
            />
          </div>
        </div>
      </div>

      <!-- 上传视频的预览 -->
      <div
        v-if="Dfolder_type == 'video'"
        class="updatevideo_All"
        v-for="(item, index) in updatevideo"
        :key="index"
      >
        <div class="updatevideo_item" @click="previewClick(item)">
          <video
            :id="item.id"
            class="updatevideo_item_s"
            :src="item.url"
          ></video>

          <!-- 已上传 -->
          <div class="up_fin" v-if="item.up_finish == true">
            <a-tag color="success">已上传</a-tag>
          </div>

          <!-- 上传失败 -->
          <div class="up_fin" v-if="item.isfailed">
            <a-tag color="red">上传失败</a-tag>
          </div>
        </div>

        <!-- 进度条  上传中 -->
        <div class="progress_item" v-if="item.up_ing && !item.up_finish">
          <a-progress
            :percent="isAlionline || isOss ? item.uploadProgress : 100"
            :showInfo="isAlionline || isOss"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
        </div>

        <!-- 进度条  待上传 -->
        <div class="before_progress_item" v-if="!item.up_ing">
          <a-progress
            style="width: 78%"
            percent="0"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
          <div class="wait_upload">待上传</div>
        </div>

        <div class="updatevideo_bottom">
          <div class="updatevideo_bottom_left">
            {{ item.name }}
          </div>

          <div class="updatevideo_bottom_right">
            <delete-outlined
              v-if="!loading"
              class="updatevideo_icon_right"
              @click="del_up(index)"
            />
          </div>
        </div>
      </div>

      <!-- 上传音频的预览 -->
      <div
        v-if="Dfolder_type == 'audio'"
        class="updatevideo_All"
        v-for="(item, index) in updateAudio"
        :key="index"
      >
        <div class="updatevideo_item" @click="previewClick(item)">
          <cu-icon
            type="icon-audio"
            style="font-size: 40px; display: flex; align-items: center"
          />

          <!-- 已上传 -->
          <div class="up_fin" v-if="item.up_finish == true">
            <a-tag color="success">已上传</a-tag>
          </div>

          <!-- 上传失败 -->
          <div class="up_fin" v-if="item.isfailed">
            <a-tag color="red">上传失败</a-tag>
          </div>
        </div>

        <!-- 进度条  上传中-->
        <div class="progress_item" v-if="item.up_ing">
          <a-progress
            :percent="isAlionline || isOss ? item.uploadProgress : 100"
            :showInfo="isAlionline || isOss"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
        </div>

        <!-- 进度条  待上传 -->
        <div class="before_progress_item" v-if="!item.up_ing">
          <a-progress
            style="width: 78%"
            percent="0"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
          <div class="wait_upload">待上传</div>
        </div>

        <div class="updatevideo_bottom">
          <div class="updatevideo_bottom_left">
            {{ item.name }}
          </div>

          <div class="updatevideo_bottom_right">
            <delete-outlined
              v-if="!loading"
              class="updatevideo_icon_right"
              @click="del_upaudio(index)"
            />
          </div>
        </div>
      </div>

      <!-- 素材列表 -->
      <div
        v-for="(item, index) in materialList"
        :key="index"
        @click="chooseFolder(item, index)"
        class="material_item_image"
      >
        <eye-filled
          v-if="item.material_type !== 'text' && item.material_type !== 'audio'"
          @click.stop="previewMaterial(item)"
          class="bottom_icon"
          :style="{}"
        />
        <div class="material_item_image_top">
          <div class="operate_con" :style="operateStyle(item)">
            <div class="top_check">
              <a-checkbox
                :disabled="
                  !multiple
                    ? !item.checked && materialCount == 1 && !multiple
                    : multiple &&
                      item.material_type === 'video' &&
                      item.material_duration < 0
                "
                @change="(value) => handleCheckChange(value, item)"
                style="margin-left: 5px"
                v-model:checked="materialList[index].checked"
              ></a-checkbox>

              <a-tag v-if="item.is_use" class="is_used" color="blue"
                >已导入</a-tag
              >

              <div class="zhanwei"></div>
            </div>
            <div class="bottom_con">
              <span
                class="material_name"
                v-if="
                  item.material_type !== 'text' &&
                  item.material_type !== 'audio'
                "
                style="color: #fff; margin: 0 5px"
                >{{ item.material_name }}</span
              >

              <span class="bottom_con_left">{{
                item.material_duration_text
              }}</span>

              <!-- <span class="material_name" v-if="item.material_type == 'audio'" style="color: #000; margin-top: 5px">{{
                item.material_name }}</span> -->
            </div>
          </div>
          <div class="material_image">
            <img v-lazy="item.thumb_url" v-if="item.thumb_url" />

            <img
              v-else-if="item.material_type == 'image' && !item.thumb_url"
              :src="item.material_url"
            />

            <template
              v-else-if="item.material_type == 'video' && !item.thumb_url"
            >
              <img v-if="item?.cover_url" :src="item.cover_url" alt="" />
              <video v-else :id="'videoPlayer_' + item.id" class="img">
                <source :src="item.material_url" type="video/mp4" />
                <source :src="item.material_url" type="video/quicktime" />
                <source :src="item.material_url" type="video/mpeg" />
                <source :src="item.material_url" type="video/3gpp" />
              </video>
            </template>

            <cu-icon
              v-if="item.material_type == 'audio'"
              type="icon-audio"
              style="font-size: 40px"
            />
          </div>

          <div class="count_Text">
            <a-tooltip
              v-if="item.usage_count"
              placement="top"
              title="素材被引用的次数"
            >
              <a-tag color="default" style="height: 16px; line-height: 16px">{{
                item.usage_count
              }}</a-tag>
            </a-tooltip>
          </div>
        </div>

        <div class="bottom-T" v-if="item.material_type == 'audio'">
          {{ item.material_name }}
        </div>

        <div class="botom-time" v-if="item.material_type == 'audio'">
          {{ item.updated_at }}
        </div>
      </div>
    </div>

    <materialPreview
      :visible="previewVisible"
      :materialDetail="materialDetail"
      @close="closePreview"
    />
  </a-spin>
</template>

<script>
// TODO 混剪上传弹窗
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  createVNode,
  ref,
  nextTick,
  onMounted,
} from "vue";
import {
  FolderOutlined,
  PlayCircleOutlined,
  EyeOutlined,
  LeftOutlined,
  CloudUploadOutlined,
  EyeFilled,
  PlusOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
import draggable from "vuedraggable";
import materialPreview from "../../sourceMaterial/modules/materialPreview.vue";
import store from "@/store";
import { message, notification } from "ant-design-vue";
import request from "../../../../../../common/utils/request";
import { upload } from "@/common/utils/uploader/index";
import defaultSetting from "@/common/utils/defaultSetting.js";
import utils from "@/common/utils/utils.js";
import axios from "axios";
import {accept}from '@/common/utils/atherUtils.js'

export default defineComponent({
  props: {
    showContent: {
      type: Array,
      default: () => {
        return [];
      },
    },
    list: {
      type: Array,
      default: () => {
        return [];
      },
    },
    isLoading: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    isTip: {
      type: Boolean,
      default: false,
    },
    Dfolder_type: {
      type: String,
      default: "",
    },
    folder_name: {
      type: String,
      default: "",
    },
    Now_merchant_folder_statck_id: {
      type: String,
      default: "",
    },
    istongyong: {
      type: Boolean,
      default: false,
    },
    useType: {
      type: String, 
      default: '',
    },
    is_tag: {
      type: Boolean,
      default: false,
    },
    // 后缀
    extension: {
      type: String,
      default:''
    },
    // 选择素材的数量
    selectNum: {
      type: Number,
      default:0
    }
  },
  components: {
    draggable,
    PlayCircleOutlined,
    EyeOutlined,
    materialPreview,
    LeftOutlined,
    CloudUploadOutlined,
    EyeFilled,
    PlusOutlined,
    DeleteOutlined,
  },
  setup(props, context) {
    const state = reactive({
      materialList: [],
      previewVisible: false,
      showBottomCount: 0,
      materialDetail: {},
      checkAll: false,
      checkeach: false,
      isHovered: false,
      queryData: {
        files: [],
      },
      BASE_URL: "",
      oss_config_Info: {},
      SetUploadPath: "",
      fileMaxSize: "",
      free_send_text: "",
      fileMaxSizeErr: "",
      All_file: [],
      iscount: 0,
      isAll_upload: true,
      Success_list: [],
      uploading_list: [],
      notCompletedCount: 0,
      // 预览效果
      updateImage: [],
      updatevideo: [],
      updateAudio: [],
      loading: false,
      ALLshouldContinuePolling: true,
      cos_progressList: [],
      oss_config: {},
      noenzu: false,
      isnum: 0,
    });

    // 上传的类型
    const getAcceptValue = computed(() => {
      switch (props.Dfolder_type) {
        case "video":
          return accept.videoAccept;
        case "image":
          return accept.imageAccept;
        case "audio":
          return props.useType == '声音克隆' ? props.extension : accept.audioAccept;
        default:
      }
    });

    const work_ai_config = computed(() => {
      return store?.state?.shotstack?.work_ai_config || {};
    });

    const isAlionline = computed(() => {
      return work_ai_config.value?.shotstack_driver == "alionline";
    });

    const isOss = computed(() => {
      return work_ai_config.value?.upload_driver == "oss";
    });

    const materialCount = computed(
      () => state.materialList.filter((item) => item.checked)?.length
    );

    const chooseFolder = (item, index) => {
      // 单选
      if (!props.multiple) {
        if (materialCount.value == 1 && !item.checked) return;
        if (materialCount.value == 1 && item.checked) {
          item.checked = false;
          context.emit("getChoose", {});
          return;
        }
        item.checked = true;

        context.emit("getChoose", item);
      } else {
        if (item?.material_type === "video" && item.material_duration < 0) {
          // message.warning("最低素材时长为3秒");
          return;
        }
        if (!item?.checked) {
          item.checked = true;
        } else {
          item.checked = false;
          // 取消勾选, 通知父组件 删除取消勾选的项
          context.emit('cancelChecked', item)
        }

        let arr = state.materialList.filter((item) => item.checked);
        context.emit("getChoose", arr);
      }
    };

    const previewMaterial = (item) => {
      console.log(item, "预览素材号");
      state.previewVisible = true;
      state.materialDetail = item;
    };

    const closePreview = () => {
      state.previewVisible = false;
      state.materialDetail = {};
    };

    const handleCheckChange = (value, obj) => {
      // 单选
      if (!props.multiple) {
        let index = state.materialList.findIndex(
          (item) => item.checked == true
        );
        if (index != -1) {
          context.emit("getChoose", obj);
        } else {
          context.emit("getChoose", {});
        }
      } else {
        obj.checked = value.target.checked;
        // 取消勾选, 通知父组件 删除取消勾选的项
        if (!obj.checked) {
          context.emit('cancelChecked', obj)
        }
        let arr = state.materialList.filter((item) => item.checked);

        context.emit("getChoose", arr);
      }
    };

    // 反选
    const downChange = () => {
      state.materialList.forEach((item, index) => {
        chooseFolder(item, index);
      });
    };

    // 全选
    const onCheckAllChange = () => {
      if (state.checkAll == true) {
        state.checkeach = false;
        state.materialList.forEach((item) => [(item.checked = true)]);
        context.emit("getChoose", state.materialList);
      } else {
        state.materialList.forEach((item) => [(item.checked = false)]);
        context.emit("getChoose", state.materialList);
      }
    };

    watch(
      () => state.materialList,
      (val) => {
        val.forEach((item) => {
          if (item.checked == false) {
            state.checkAll = false;
          }
        });
      },
      { deep: true }
    );

    const backPrevious = () => {
      context.emit("back");
    };

    const uploadMaterial = () => {
      context.emit("uploadMaterial");
    };

    const operateStyle = computed(() => {
      return function (item) {
        return {
          backgroundColor: props.multiple
            ? item?.material_type === "video" && item.material_duration < 0
              ? "rgba(255,255,255,.6)"
              : ""
            : !item.checked && materialCount.value == 1 && !props.multiple
            ? `rgba(255,255,255,.6)`
            : ``,
        };
      };
    });

    const initVideo = () => {
      if (
        state.materialList?.length &&
        state.materialList[0].material_type == "video"
      ) {
        nextTick(() => {
          state.materialList.map((item) => {
            const dom = document.getElementById("videoPlayer_" + item.id);
            dom && (dom.currentTime = 5);
          });
        });
      }
    };

    const getaliinfo = async () => {
      await request
        .get("/work_ai", "/material/upload/info", {
          merchant_folder_statck_id: props.Now_merchant_folder_statck_id,
          upload_from: "",
        })
        .then((res) => {
          if (res.code == 1001) {
            state.noenzu = true;
          }
          if (res.result) {
            state.SetUploadPath = res.result.upload_path;
            state.fileMaxSize = res.result.fileMaxSize;
            state.free_send_text = res.result.free_send_text;
            state.fileMaxSizeErr = res.result.fileMaxSizeErr;
          }
        });
    };


    const getFileType = (file) => {
      // 如果 file.type 不为空，直接返回
      if (file.type) return file.type;

      // 基于扩展名推测 MIME 类型
      const extension = file.name.split('.').pop().toLowerCase();
      const mimeTypes = {
        mov: 'video/quicktime',
        mp4: 'video/mp4',
        '3gp': 'video/3gpp',
        jpg: 'image/jpeg',
        jpeg: 'image/jpeg',
        png: 'image/png',
        mp3: 'audio/mpeg',
        m4a: 'audio/mp4',
        wav: 'audio/wav',
        ogg: 'audio/ogg',
        pcm: 'audio/pcm',
      };
      return mimeTypes[extension] || '';
    };

    // 上传前的准备
const beforeUpload = async (file, fileList) => {
  state.queryData.files = fileList;

  const rejectFile = (msg) => {
    message.error(msg);
    state.fileList = fileList.filter(item => item.uid !== file.uid);
    state.queryData.files = fileList.filter(item => item.uid !== file.uid);
    return false;
  };

  const mimeType = getFileType(file).split('/')[0]
  // console.log(mimeType, '文件类型');
  console.log(mimeType, '文件类型');
  console.log(file, fileList,'文件雷彪');
  
  if(mimeType == 'video') {
    return new Promise((resolve) => {
      if (file.size / 1024 / 1024 / 1024 >= 1) {
        resolve(rejectFile("视频文件不可大于 1GB!"));
        return;
      }

      const video = document.createElement("video");
      const blobURL = URL.createObjectURL(file);
      video.src = blobURL;

      video.onloadedmetadata = () => {
        URL.revokeObjectURL(blobURL); 

        if (video.duration > 3600) {
          resolve(rejectFile("视频文件不能大于 60 分钟时长!"));
          return;
        }

        if (video.videoWidth > 4096 || video.videoHeight > 4096) {
          resolve(rejectFile("视频最大不能超过 4096px!"));
          return;
        }

        resolve(true);
      };
    });
  }else if (mimeType == 'image') {
    return new Promise((resolve) => {
      if (file.size / 1024 / 1024 >= 20) {
        resolve(rejectFile("文件不可大于 20M!"));
        return;
      }

      const reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = (e) => {
        const image = new Image();
        image.src = e.target.result;

        image.onload = () => {
          if (image.width <= 49 || image.height <= 49) {
            resolve(rejectFile("图片宽度不能小于50px"));
            return;
          }

          if (image.width >= 8000 || image.height >= 8000) {
            resolve(rejectFile("图片宽度不能大于8000px"));
            return;
          }

          resolve(true);
        };
      };
    });
  }else if (mimeType == 'audio') {
    return new Promise((resolve) => {
      const index = file.name.lastIndexOf('.');
      let name
      if (index!== -1) {
      name = file.name.slice(index + 1);
      name && (name = name.toLowerCase());
      }
      console.log(name,'截取的name');

      const fileType = props.useType == '声音克隆' ? ['mp3', 'm4a', 'wav','ogg', 'm4a', 'pcm'] : ['mp3', 'm4a', 'wav']
      if (!fileType.includes(name)) {
        console.log(name,'不支持的格式');
        resolve(rejectFile(`不支持${name}文件类型`));
        return;
      }
      resolve(true);
    });
  }else {
    rejectFile("不支持的文件类型");
  }
};

    //  手动上传
    const customRequest = async () => {
      state.iscount += 1;
      if (state.iscount !== state.queryData.files.length) return;

      state.loading = true;
      // 上传效果渲染
      console.log(state.queryData.files,   '待渲染的数组11111111');
      state.queryData.files.forEach((item) => {
        const baseObject = {
          url: URL.createObjectURL(item),
          name: item.name,
          id: item.uid,
          up_ing: false,
          up_finish: false,
          uploadProgress: 0,
          isfailed: false,
        };
        switch (props.Dfolder_type) {
          case "image":
            state.updateImage.push({ ...baseObject });
            break;
          case "video":
            state.updatevideo.push({ ...baseObject, isplayshow: true });
            break;
          case "audio":
            state.updateAudio.push({ ...baseObject });
            break;
          default:
        }
      });
      // ----------------------cos---------------------------
      const uploadQueue = [];
      const MAX_CONCURRENT_UPLOADS = 3;

      state.BASE_URL = defaultSetting.requestDomain;
      if (process.env.NODE_ENV === "development") {
        state.BASE_URL = state.BASE_URL + "/api";
      }

      function uploadFile(file, index) {
        return new Promise((resolve, reject) => {
          request
            .post("/work_ai", "/material/get/capacity")
            .then((res) => {
              const remainingCapacity = parseInt(res.result.remainingCapacity, 10);

              const typeParts = file.type.split("/");
              const mimeType = typeParts[0];
              if (remainingCapacity < file.size) {
                message.error(`存储空间不足，无法上传文件：${file.name}`);
                resolve();
              } else {
                const formData = new FormData();
                formData.append("file", file);
                formData.append("type", mimeType);
                formData.append("scene", mimeType);
                formData.append(
                  "merchant_folder_statck_id",
                  props.Now_merchant_folder_statck_id
                );
                formData.append("org_id", utils.getOrgId());
                formData.append("user_token", utils.getToken());
                formData.append(
                  "cur_env",
                  utils.isMobile()
                    ? "h5"
                    : import.meta.env.ELECTRON
                    ? "desktop"
                    : "pc"
                );
                formData.append("team_id", utils.getCurrentTeam());
                formData.append("path_synchronous", "1");

                axios({
                  method: "post",
                  url: `${state.BASE_URL}/work_ai/material/upload`,
                  data: formData,
                  headers: {
                    "Content-Type": "multipart/form-data",
                    "Org-Token": utils.getToken(),
                  },
                })
                  .then((response) => {
                    if (response?.data?.data?.errorData.length > 0) {
                      notification.warn({
                        message: response.data.data.errorData[0],
                        duration: 2,
                      });
                      resolve();
                    } else {
                      handleUploadSuccess(response, index)
                        .then(resolve)
                        .catch(reject);
                    }
                  })
                  .catch(reject);
              }
            })
            .catch(reject);
        });
      }

      // 处理上传成功的逻辑
      async function handleUploadSuccess(response, index) {
        state.cos_progressList[index].is_uping = true;
        switch (props.Dfolder_type) {
          case "image":
            state.updateImage[index].up_ing = true;
            break;
          case "video":
            state.updatevideo[index].up_ing = true;
            break;
          case "audio":
            state.updateAudio[index].up_ing = true;
            break;
        }
        let pollInterval;
        let shouldContinuePolling = true;

        pollInterval = setInterval(async () => {
          if (!state.ALLshouldContinuePolling) {
            clearInterval(pollInterval);
            return;
          }
          if (!shouldContinuePolling) {
            clearInterval(pollInterval);
            return;
          }

          await request
            .get("/work_ai", "/material/upload/status", {
              taskId: response.data?.data?.returnData[0]?.taskId,
            })
            .then(async (res) => {
              if (res.status === 1) {
                // 继续轮询
              } else if (res.status === 2) {
                shouldContinuePolling = false;
                clearInterval(pollInterval);

                await markUploadComplete(index);
              } else if (res.status === 3) {
                shouldContinuePolling = false;
                message.error("上传失败");
                clearInterval(pollInterval);
              }
            })
            .catch((error) => {
              clearInterval(pollInterval);
            });
        }, 2000);

        return new Promise((resolve) => {
          setTimeout(resolve, 5000);
        });
      }

      // 标记上传完成
      async function markUploadComplete(index) {
        state.cos_progressList[index].is_uping = false;
        state.cos_progressList[index].is_upfinish = true;
        store.dispatch("SetCosProgresslist", state.cos_progressList);
        switch (props.Dfolder_type) {
          case "image":
            state.updateImage[index].up_ing = false;
            state.updateImage[index].up_finish = true;
            if (state.updateImage.every((item) => item.up_finish === true)) {
              message.success("上传成功");
              state.updateImage = [];
              state.loading = false;
              state.queryData.files = [];
              state.loading = false;
  
              // getInfo();
            }
            break;
          case "video":
            state.updatevideo[index].up_ing = false;
            state.updatevideo[index].up_finish = true;
            if (state.updatevideo.every((item) => item.up_finish === true)) {
              message.success("上传成功");
              state.updatevideo = [];
              state.loading = false;
              state.queryData.files = [];
              state.loading = false;
  
              // getInfo();
            }
            break;
          case "audio":
            state.updateAudio[index].up_ing = false;
            state.updateAudio[index].up_finish = true;
            if (state.updateAudio.every((item) => item.up_finish === true)) {
              message.success("上传成功");
              state.updateAudio = [];
              state.loading = false;
              state.queryData.files = [];
              state.loading = false;
      

              // getInfo();
            }
            break;
        }
      }

      // Cos上传
      async function startUploads() {
        // 增加进度条 状态值
        state.cos_progressList = state.queryData.files.map((item) => {
          return {
            ...item,
            is_uping: false,
            is_upfinish: false,
            name: item.name,
          };
        });
        store.dispatch("SetCosProgresslist", state.cos_progressList);

        for (let i = 0; i < state.queryData.files.length; i++) {
          const file = state.queryData.files[i];
          uploadQueue.push(uploadFile(file, i));

          if (uploadQueue.length > MAX_CONCURRENT_UPLOADS) {
            await uploadQueue.shift();
          }
        }

        // 等待所有上传任务完成
        await Promise.all(uploadQueue);
      }

      //  --------------------oss---------------------------

              // 上传成功的id数组
      const uploadSuccessIds = ref([])

      // 控制并发数量的函数
      async function processQueue(queue, concurrency) {
        const runningTasks = new Set();
        const results = [];

        const addTask = async () => {
          if (queue.length === 0) {
            return;
          }

          const task = queue.shift();
          const promise = task()
            .then((res) => {
              if (res == undefined) {
                res = false;
              }
              results.push(res);
              runningTasks.delete(promise);
              addTask();
            })
            .catch((error) => {
              results.push(null);
              runningTasks.delete(promise);
              addTask();
            });

          runningTasks.add(promise);
        };

        for (let i = 0; i < concurrency; i++) {
          addTask();
        }

        while (runningTasks.size > 0 || queue.length > 0) {
          await Promise.race(runningTasks);
        }

        return results;
      }

      // Oss上传
      async function startOssUploads() {
        await getOss_config();
        if ((Object.keys(state.oss_config).length = 0)) {
          await getOss_config();
        }
        let upDataList = state.queryData.files.map((item) => ({
          ...item,
          name: item.name,
          id: item.uid,
          state: 0,
          percent: 0,
          iscancel: false,
        }));

        // 将上传数据 同步至vuex
        store.dispatch("SetUpDateList", upDataList);

        const uploadQueue = state.queryData.files.map((file, i) => async () => {
          switch (props.Dfolder_type) {
            case "image":
              state.updateImage[i].up_ing = true;
              break;
            case "video":
              state.updatevideo[i].up_ing = true;
              break;
            case "audio":
              state.updateAudio[i].up_ing = true;
              break;
          }
          // 可选的配置对象
          const config = {
            SetUploadPath: state.SetUploadPath,
            oss_config: state.oss_config,
          };
          const res = await upload(file, config);
          if(!res.fileUrl){
            // 如果没有成功上传的 将不需要执行到下一个接口
            if(props.Dfolder_type=='image'){
              if(state.updateImage.length>0){
                state.updateImage = state.updateImage.filter((item)=>{
                  return item.name.split(".")[0] != res.name
                })
              }
            }

            if(props.Dfolder_type=='video'){
              if(state.updatevideo.length>0){
                state.updatevideo = state.updatevideo.filter((item)=>{
                  return item.name.split(".")[0] != res.name
                })
              }
            }

            if(props.Dfolder_type=='audio'){
              if(state.updateAudio.length>0){
                state.updateAudio = state.updateAudio.filter((item)=>{
                  return item.name.split(".")[0] != res.name
                })
              }
            }
            state.loading = false
            return
          }
          const typeParts = file.type.split("/");
          const mimeType = typeParts[0];
          //  oss 上传完成  开始上传至后端
          let up_paramas = {
            merchant_folder_statck_id: props.Now_merchant_folder_statck_id,
            material_type: mimeType,
            material_name: file.name,
            material_url: res.fileUrl,
            material_size: file.size,
          };
          const response = await request.post(
            "/work_ai",
            "/user/mobile/media",
            up_paramas
          );
          console.log(response,'同步到后端');

          uploadSuccessIds.value.push(response.result)

          switch (props.Dfolder_type) {
            case "image":
              state.updateImage[i].up_finish = true;
              break;
            case "video":
              state.updatevideo[i].up_finish = true;
              break;
            case "audio":
              state.updateAudio[i].up_finish = true;
              break;
          }
          return response;
        });

        const results = await processQueue(uploadQueue, 2);

        // 计算成功的总数
        state.isnum = results.reduce(
          (acc, res) => acc + (res?.result ? 1 : 0),
          0
        );

        if (results.every((res) => res?.result) && state.isAll_upload) {
          message.success("上传完成!");
          context.emit('refreshList', JSON.parse(JSON.stringify(uploadSuccessIds.value)))
          uploadSuccessIds.value = []
          state.loading = false;
          state.queryData.files = [];
          state.iscount = 0;

          // 清空占位数据??
          switch (props.Dfolder_type) {
            case "image":
              state.updateImage = [];
              break;
            case "video":
              state.updatevideo = [];
              break;
            case "audio":
              state.updateAudio = [];
              break;
            default:
          }
          // await getInfo();
        }
      }

      // 判断驱动
      if (isAlionline.value || isOss.value) {
        // oss上传
        await getaliinfo();
        startOssUploads();
      } else {
        // cos上传
        startUploads();
      }
    };

    const getOss_config = async () => {
      const response = await request.post(
        "/work_ai",
        "/upload/oss/config/ststoken",
        {
          isRefresh: "1",
        }
      );
      if (response.sts) {
        state.oss_config = response.sts;
      }
    };

    // 删除预览
    const del_up = (index) => {
      state.updatevideo.forEach((item) => {
        const videoElement = document.getElementById(item.id);
        if (videoElement) {
          videoElement.pause();
          item.isplayshow = true;
        }
      });
      if (index >= 0 && index < state.updatevideo.length) {
        state.updatevideo.splice(index, 1);
        state.queryData.files.splice(index, 1);
      }
    };

    // 删除_音频预览
    const del_upaudio = (index) => {
      if (index >= 0 && index < state.updateAudio.length) {
        state.updateAudio.splice(index, 1);
        state.queryData.files.splice(index, 1);
      }
    };

    // 删除_图片预览
    const del_upImage = (index) => {
      if (index >= 0 && index < state.updateImage.length) {
        state.updateImage.splice(index, 1);
        state.queryData.files.splice(index, 1);
      }
    };

    const previewClick = (data) => {
      let materialData = {
        material_type: props.Dfolder_type,
        material_url: data.url,
        material_name: data.name,
      };
      state.previewVisible = true;
      state.materialDetail = materialData;
    };

    //  刷新页面
    const getInfo = async () => {
      const extensions = props.extension.split(",").map(ele => ele.replace(/^\.+/, ''))
      
      request
        .post("/work_ai", "/user/shotstack/media/list", {
          merchant_folder_statck_id: props.Now_merchant_folder_statck_id,
          extensions: extensions?.[0] ? extensions : null,
        })
        .then((res) => {
          state.materialList = res.result.data;
          state.total = res.result?.total
          switch (props.Dfolder_type) {
            case "image":
              state.updateImage = [];
              break;
            case "video":
              state.updatevideo = [];
              break;
            case "audio":
              state.updateAudio = [];
              break;
            default:
          }

          if (state.isnum !== 0) {
            for (let i = 0; i < state.isnum; i++) {
            state.materialList[i].checked = true;
              let arr = state.materialList.filter((item) => item.checked);
              console.log(arr, '选择的素材列表____________');

              if (props.multiple) {
                context.emit("getChoose", arr);
              } else {
                // if (!arr?.[0]) { 
                //   return message.error('请选择素材!')
                // }
                context.emit("getChoose", arr?.[0] ?? {});
              }
            
            }

            state.isnum = 0
          }
        });
    };

    onMounted(() => {
      state.materialList = props.list;
      state.materialList.map((item) => {
        typeof item?.checked !== 'boolean' && (item.checked = false)
        item.isHovered = false;
        item.is_use = false;
      });

      initVideo();
    });

    watch(
      () => props.list,
      (val) => {
        state.materialList = val;
        state.materialList.map((item) => {
          typeof item?.checked !== 'boolean' && (item.checked = false)
          item.is_use = false;
        });

        props.showContent.forEach((v1) => {
          state.materialList.forEach((v2) => {
            console.log(v1?.id, 'id是啥??');
            if (typeof v1?.id == 'string') {
              if (v1?.id?.split("_")?.[1] == v2.id) {
              v2.is_use = true;
            }
            } else {
              if (v1?.id == v2.id) {
              v2.is_use = true;
            }
            }
          });
        });
        initVideo();
      }
    );

    // 进度条
    watch(
      () => store.state.user.uploadProgress,
      (val) => {
        switch (props.Dfolder_type) {
          case "image":
            state.updateImage.forEach((v1) => {
              val.forEach((v2) => {
                if (v1.name == v2.filename) {
                  v1.uploadProgress = v2.uploadProgress;
                }
              });
            });
            break;
          case "video":
            state.updatevideo.forEach((v1) => {
              val.forEach((v2) => {
                if (v1.name == v2.filename) {
                  v1.uploadProgress = v2.uploadProgress;
                }
              });
            });
            break;
          case "audio":
            state.updateAudio.forEach((v1) => {
              val.forEach((v2) => {
                if (v1.name == v2.filename) {
                  v1.uploadProgress = v2.uploadProgress;
                }
              });
            });
            break;
        }
      },
      {
        deep: true,
      }
    );

const dynamicStyle = computed(() => props.is_tag ? { paddingLeft: '20px' } : {});

    return {
      ...toRefs(state),
      chooseFolder,
      previewMaterial,
      closePreview,
      handleCheckChange,
      backPrevious,
      uploadMaterial,
      operateStyle,
      initVideo,
      materialCount,
      downChange,
      onCheckAllChange,
      getAcceptValue,
      beforeUpload,
      customRequest,
      getaliinfo,
      isAlionline,
      isOss,
      work_ai_config,
      del_upImage,
      del_up,
      del_upaudio,
      previewClick,
      dynamicStyle
    };
  },
});


</script>

<style lang="less" scoped>
.no_data {
  color: 14px;
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.top_con {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .left_back {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 14px;

    &:hover {
      color: #0076ff;
    }
  }

  .top_con-right {
    display: flex;
    justify-content: space-between;
    padding-right: 10px;
  }
}

.material_con {
  width: 100%;
  max-height: 430px;
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  overflow-y: scroll;
  margin-top: 10px;
  flex-direction: row;
  align-items: stretch;
  justify-content: flex-start;
  align-content: flex-start;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  .custom_upload {
    width: 225px;
    height: 178px;
    background: #f9f9f9 !important;
    border: 3px dashed #ddd;
    color: #696969;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    cursor: pointer;
    margin-left: 10px;
    margin-top: 10px;

    .upload_txt {
      margin-top: 5px;
    }
  }

  .material_item_image {
    // margin-left: 20px;
    margin-right: 20px;
    margin-bottom: 10px;
    position: relative;

    &:hover {
      & .bottom_icon {
        opacity: 1;
      }

      & .operate_con {
        background: #00000041;
        border-radius: 10px;
      }
    }

    // 预览的小眼睛
    .bottom_icon {
      margin-right: 5px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      opacity: 0;
      transition: all 0.3s ease;
      z-index: 100;
      color: #ffffff;
      font-size: 25px;

      &:hover {
        color: var(--ss-primary-3);
      }
    }

    // 头部操作栏
    .material_item_image_top {
      width: 225px;
      height: 200px;
      cursor: pointer;
      flex-shrink: 0;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      background-color: #000;
      border-radius: 10px;

      .count_Text {
        position: absolute;
        right: 8px;
        top: 8px;
        z-index: 9999 !important;

        .count_Text_icon {
          font-size: 18px;
          color: #fff;
          margin-right: 3px;
        }

        .count_Text_wenan {
          color: #fff;
        }
      }
    }

    // 盖在卡片上的遮罩层 + 上下操作栏
    .operate_con {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 99;
      transition: all 0.3s ease;

      .top_check {
        position: absolute;
        left: 0;
        top: 1px;
        width: 100%;
        height: 25px;
        display: flex;
        justify-content: space-between;

        .zhanwei {
          margin-right: 5px;
        }
      }

      // 底部名称
      .bottom_con {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        line-height: 24px;
        display: flex;
        justify-content: space-between;
        text-align: start;
        align-items: center;
        background: #000000a4;
        font-size: 13px;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;

        .material_name {
          width: 225px;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    // 图片
    .material_image {
      // width: 225px;
      // height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 98%;
      height: auto;
      background-color: rgb(0, 0, 0);
      position: relative;
      overflow: hidden;

      .video_duration {
        position: absolute;
        right: 3px;
        top: 0px;
        color: #fff;
      }

      img {
        max-width: 225px;
        max-height: 195px;
      }

      video {
        max-width: 225px;
        max-height: 200px;
      }
    }
  }
}

.bottom_pagination{

}

.bottom-T {
  width: 180px;
  margin-left: 10px;
  font-weight: 700 !important;
  margin-top: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.botom-time {
  width: 180px;
  margin-left: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bottom_con_left {
  padding-right: 5px;
}

:deep(.model_upload) {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 225px !important;
  height: 200px !important;
  border: none;
  border: 1px dashed #ccc;
  border-radius: 10px;
  background-color: #f8f8f8;
}

:deep(.ss-upload.ss-upload-select-picture-card) {
  width: 200px !important;
  height: 200px !important;
  border-bottom-left-radius: 10px !important;
  border-bottom-right-radius: 10px !important;
  border: none !important;
}

.model_upload_text {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
  padding: 0 10px;
  flex-direction: column;
}
:deep(.ss-upload-select-text) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  color: #696969 !important;
  // background-color: pink !important;
}

.model_upload_top {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 5px;
}

.updatevideo_All {
  // margin-left: 20px;
  margin-right: 20px;
  margin-bottom: 10px;
}
.updatevideo_All:nth-child(3n + 1) {
  margin-left: 0;
}

.updatevideo_item {
  height: 154px;
  width: 225px;
  background-color: #000;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  // align-items: center;
  position: relative;

  .up_fin {
    position: absolute;
    bottom: 10px;
    right: -8px;
  }

  .updatevideo_item_s {
    width: 100%;
  }
}

.updatevideo_bottom {
  width: 225px;
  display: flex;
  justify-content: space-between;

  .updatevideo_bottom_left {
    width: 80%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.updatevideo_icon_right {
  font-size: 16px;
  margin-right: 20px;
}

.play_video {
  color: #fff;
  font-size: 33px;
  position: absolute;
  top: 43%;
}

.big-box {
  height: 390px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
}

.select_icon {
  font-size: 16px;
  margin-left: 10px;
}

.line {
  height: 1px;
  width: 760px;
  background-color: #e5e5e5;
  margin: 10px 0 20px 0;
}

.text-content {
  height: 320px;
  overflow: auto;
}

.see_img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.btn_btn {
  margin-bottom: 6px;
  border-radius: 6px;
  color: #fff;
  border: none;
}

.baseModel {
  :deep(.ss-modal-footer) {
    border-top: none !important;
  }

  :deep(.ss-modal-body) {
    padding-top: 30px !important;
  }

  :deep(.ss-modal) {
    width: 410px !important;
  }
}

.empty_box {
  background-color: #fff;
  width: 100%;
  height: 52px;
}

.before_progress_item {
  display: flex;
  width: 100%;
}

.wait_upload {
  color: #f7a726;
  font-size: 10px;
}

.upload_mater {
  margin-right: 20px;
  margin-bottom: 20px;
}
</style>
